<template>
  <el-row :span="24" class="model-manage">
    <el-form :model="form">
      <el-col :span="24">
        <el-col :span="7">
          <el-form-item label="项目名称" label-width="70px">
            <el-select
              v-model="form.pro_id"
              @change="getModelManageToken('watch')"
              class="sel-style"
              placeholder="请选择"
            >
              <el-option
                v-for="item in proArr"
                :key="item.project_id"
                :label="item.project_name"
                :value="item.project_id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="专业类别" label-width="90px">
            <el-select
              v-model="form.major_cate"
              clearable
              filterable
              multiple
              collapse-tags
              class="sel-style"
              placeholder="请选择"
            >
              <el-option
                v-for="item in majorCateArr"
                :key="item.value"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="模型名称" label-width="90px">
            <el-input v-model="form.model_name" placeholder="请输入模型名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3" class="search-style">
          <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-col>
      </el-col>
    </el-form>
    <el-col :span="24" class="opr-button">
      <el-button type="primary" icon="el-icon-upload2" @click="onUpload">上传</el-button>
      <el-button type="success" icon="el-icon-download" @click="onDown">插件下载</el-button>
    </el-col>
    <el-col :span="24">
      <el-table
        stripe
        style="width: 100%"
        height="600px"
        :header-cell-style="{ background: '#f5f5f5' }"
        :data="tableData"
      >
        <el-table-column type="index" label="序号" align="center" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column label="项目名称" prop="projectName" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="modelName" label="模型名称" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="modelTag" label="专业类别" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="modelSize" label="模型大小" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="220px" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="onEdit(scope.row)">编辑</el-button>
            <el-button type="text" @click="onLook(scope.row)">查看</el-button>
            <el-button type="text" @click="deleteModel(scope.row)">删除</el-button>
            <el-button type="text" @click="updateModel(scope.row)">更新模型</el-button>
            <el-button type="text" @click="onShare(scope.row)">分享</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
    <el-col :span="24" class="bottom-style">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="form.page"
        :page-sizes="[10, 20, 50, 100,200]"
        :page-size="form.page_size"
        align="center"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-col>
    <el-dialog
      :title="todos==1?'上传模型':todos==2?'编辑':'更新模型'"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <AddOrModifyModel
        :todos="todos"
        :objRow="objRow"
        :catchSave="catchSave"
        :catchBack="catchBack"
      ></AddOrModifyModel>
    </el-dialog>
    <el-dialog
      title="查看版本"
      :visible.sync="dialogVisibleVer"
      width="40%"
      :before-close="handleCloseVer"
    >
      <LookVer :callBackVer="callBackVer" :todosVer="todosVer"></LookVer>
    </el-dialog>

    <el-dialog
      title="分享链接"
      :visible.sync="dialogVisibleShare"
      width="50%"
      :before-close="handleCloseShare"
    >
      <el-row>
        <el-form :model="requestParams" label-width="80px">
          <el-col :span="24">
            <el-form-item label="版本号">
              <el-select v-model="requestParams.verNo" @change="onVerChange" placeholder="请选择">
                <el-option
                  v-for="item in verArr"
                  :key="item.id"
                  :label="item.versionName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模型地址">
              <el-input :disabled="true" v-model="requestParams.modelAdrr">
                <template slot="append" class="copy-style">
                  <el-tooltip placement="top">
                    <div slot="content">点击复制</div>
                    <el-button
                      class="tag-read"
                      :data-clipboard-text="requestParams.modelAdrr"
                      @click="onCopy"
                    >复制</el-button>
                  </el-tooltip>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="share-bottom-box">
            <el-button @click="verCancel">取消</el-button>
            <el-button @click="verCancel" type="primary">确定</el-button>
          </el-col>
        </el-form>
      </el-row>
    </el-dialog>
  </el-row>
</template>

<script>
import { standardCodeApi } from "@/services/StandardCode";
import AddOrModifyModel from "./components/AddOrModifyModelDialog";
import LookVer from "./components/LookVerDialog";
import { ProjectListApi } from "@/services/ProjectCenter";
import { ModelManageApi, ModelManageGetApi } from "@/services/WorkCenter";
export default {
  components: {
    AddOrModifyModel,
    LookVer
  },
  data() {
    return {
      verArr: [],
      lookVerObj: {},
      todosVer: "",
      requestParam: {
        page: 1,
        per_page: 300
      },
      requestParams: {
        modelAdrr: "",
        verNo: "",
        handleProjectId: "",
        handleTaskId: ""
      },
      dialogVisibleShare: false,
      dialogVisibleVer: false, //查看版本
      objRow: {},
      todos: 0,
      dialogVisible: false,
      proArr: [], //项目列表
      tableData: [],
      majorCateArr: [], //专业类型数组
      form: {
        pro_id: "",
        major_cate: [],
        model_name: "",
        page: 1,
        page_size: 10
      },

      total: 0
    };
  },
  watch: {
    getProjectInfo: {
      handler(newval) {
        this.proArr = newval || [];
        this.form.pro_id = newval[0].project_id || "";
        console.log(newVal, "9999");
        this.getModelManageToken("watch"); //获取token值
      },
      deep: true
    }
  },
  computed: {
    getProjectInfo() {
      let stateArray = this.$store.state.choosedProjectList.list;
      let localArray = JSON.parse(
        window.localStorage.getItem("choosedProjectList")
      );
      let projectArray = !stateArray ? localArray : stateArray;
      // this.requestParams.project_id = projectArray.join(',')
      return projectArray;
    }
  },
  methods: {
    // 删除模型
    deleteModel(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          ModelManageApi.deleteModel({
            data: [row.modelId]
          }).then(res => {
            if (res.success) {
              this.$message.success("删除成功");
            }
            this.getModelManage();
          });
        })
        .catch(() => {});
    },
    verCancel() {
      //版本的取消和确定的事件
      this.dialogVisibleShare = false;
      this.$options.data().requestParams; //重置
    },
    onVerChange(val) {
      //版本号更新时触发的事件
      this.verArr.forEach(ele => {
        if (ele.id == val) {
          this.requestParams.handleProjectId = ele.handleProjectId;
          this.requestParams.handleTaskId = ele.handleTaskId;
        }
      });
      this.requestParams.modelAdrr = ""; //重置
      // this.requestParams.modelAdrr = 'https://qlh.huizhucloud.com/index.html?projectId=' + this.requestParams.handleProjectId + '&modelId=' + this.requestParams.handleTaskId;//默认查看第一条
      this.requestParams.modelAdrr =
        "http://vothing.huizhucloud.com/index.html/#/?projectId=" +
        this.requestParams.handleProjectId +
        "&modelId=" +
        this.requestParams.handleTaskId +
        "&isPreview=1"; //默认查看第一条
    },
    // 获取项目列表
    getProjectList() {
      return ProjectListApi.getProjectList({
        params: this.requestParam
      }).then(
        res => {
          if (res.code === 0) {
            this.proArr = res.data.list;
          }
        },
        err => {
          console.log(err);
        }
      );
    },
    onCopy() {
      //复制
      var clipboard = new this.Clipboard(".tag-read");
      clipboard.on("success", e => {
        this.$message.success("复制成功");
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on("error", e => {
        // 不支持复制
        // console.log('该浏览器不支持自动复制')
        // 释放内存
        clipboard.destroy();
      });
    },
    handleCloseShare(done) {
      //分享链接关闭前触发的事件
      this.verCancel();
      done();
    },
    handleCloseVer(done) {
      //查看版本关闭前触发的事件
      this.todosVer = "";
      done();
    },
    catchSave() {
      //上传模型子组件点击保存时触发的事件
      this.catchBack();
      this.onSearch();
    },
    catchBack() {
      //上传模型子组件点击取消时触发的事件
      this.todos = 0;
      this.objRow = {};
      this.dialogVisible = false;
    },
    handleClose(done) {
      this.todos = 0;
      done();
    },
    onUpload() {
      //上传
      this.todos = 1;
      this.$set(this.objRow, "majorCateArr", this.majorCateArr);
      this.$set(this.objRow, "proArr", this.proArr);
      this.$set(this.objRow, "pro_id", this.form.pro_id);
      this.dialogVisible = true;
    },
    onDown() {
      //插件下载
      let a = document.createElement("a");
      // let path = 'https://adpmp-qlh.oss-cn-hongkong.aliyuncs.com/upload/20210414/14eed8792baeb2238f754b772a2a6b6c.exe'
      // let path = "https://cloud.huizhucloud.com/rvtstatic/BIMe_for_Revit.exe"//说明：2021.08.13更新
      let path =
        "http://hibuilding-new.oss-cn-hangzhou.aliyuncs.com/res/revit%E8%BD%AC%E6%8D%A2%E6%8F%92%E4%BB%B6.zip";
      // a.download = '插件下载.exe'//设置下载的文件名
      a.href = path; // 设置图片的下载地址
      a.click(); //触发下载事件
    },
    onSearch() {
      //查询
      this.getModelManageToken("watch");
    },
    onReset() {
      //重置
      this.form.major_cate = [];
      this.form.model_name = "";
      this.getModelManageToken("created");
    },
    getVerList(val) {
      //获取版本号
      ModelManageApi.getVerList({
        params: {
          modelId: val
        }
      })
        .then(res => {
          this.verArr = [];
          this.verArr = res.data;
          this.requestParams.verNo = this.verArr[0].id;
          this.requestParams.handleProjectId = this.verArr[0].handleProjectId; //默认版本第一个
          this.requestParams.handleTaskId = this.verArr[0].handleTaskId; //默认版本第一个
          this.requestParams.modelAdrr = ""; //重置
          // this.requestParams.modelAdrr = 'https://qlh.huizhucloud.com/index.html?projectId=' + this.requestParams.handleProjectId + '&modelId=' + this.requestParams.handleTaskId;//默认查看第一条
          this.requestParams.modelAdrr =
            "http://vothing.huizhucloud.com/index.html/#/?projectId=" +
            this.requestParams.handleProjectId +
            "&modelId=" +
            this.requestParams.handleTaskId +
            "&isPreview=1"; //默认查看第一条
        })
        .catch(error => {
          console.log(error);
        });
    },
    onShare(row) {
      //分享
      // console.log('分享row=', row.modelId)
      this.getVerList(row.modelId);
      this.dialogVisibleShare = true;
    },
    updateModel(row) {
      //更新模型
      this.todos = 3;
      this.objRow = Object.assign({}, row);
      this.dialogVisible = true;
    },
    onEdit(row) {
      //编辑
      this.todos = 2;
      this.objRow = Object.assign({}, row);
      this.$set(this.objRow, "majorCateArr", this.majorCateArr);
      this.$set(this.objRow, "proArr", this.proArr);
      this.dialogVisible = true;
    },

    callBackVer(val) {
      //查看版本弹框中点击任意一个版本的传值（子->父）
      console.log("handleTaskId=", val);
      this.lookVerObj = {};
      this.lookVerObj = val;
      // this.$set(this.lookVerObj, 'modelUrlTure', 'http://vothing.huizhucloud.com/index.html?projectId=' + val.handleProjectId + '&modelId=' + val.handleTaskId);
      this.$set(
        this.lookVerObj,
        "modelUrlTure",
        "http://vothing.huizhucloud.com/index.html/#/?projectId=" +
          val.handleProjectId +
          "&modelId=" +
          val.handleTaskId
      ) + "&isPreview=1";
      this.$router.push({
        path: "/modelLook",
        query: { lookVerObjVal: JSON.stringify(this.lookVerObj) }
      });

      // http://vothing.huizhucloud.com/index.html?projectId=${项目id变量}&modelId=${taskId变量}&isPreview=1
    },
    onLook(row) {
      //查看
      this.todosVer = row.modelId;
      this.dialogVisibleVer = true;
    },
    handleSizeChange(val) {
      //每页显示的条数解谜时触发的事件
      this.form.page_size = val;
      this.handleCurrentChange(1);
    },
    handleCurrentChange(val) {
      //当前页改变时触发的事件
      this.form.page = val;
      this.getModelManage("watch");
    },
    // 获取专业类型标准码
    getMajorTypeCode() {
      return standardCodeApi
        .getStandardCodeData({
          data: {
            code_type: "majorCateNo"
          }
        })
        .then(
          res => {
            if (res.code === 0 && res.data.list) {
              this.majorCateArr = res.data.list;
              window.localStorage.setItem(
                "majorCateNo",
                JSON.stringify(this.majorCateArr)
              );
            }
          },
          err => {
            console.log(err);
          }
        );
    },
    getModelManage() {
      //获取模型管理
      let objVal = {
        thirdPartProjectId: this.form.pro_id,
        modelName: this.form.model_name,
        modelTag: this.form.major_cate.join(","),
        size: this.form.page_size,
        current: this.form.page
      };
      ModelManageApi.getModelList({
        params: { ...objVal }
      })
        .then(res => {
          this.tableData = res.data.records;
          let proName = "";
          if (this.tableData.length > 0) {
            if (this.proArr.length > 0) {
              this.proArr.forEach(ele => {
                if (ele.project_id == this.form.pro_id) {
                  proName = ele.project_name;
                }
              });
              this.tableData.forEach(ele1 => {
                this.$set(ele1, "projectName", proName);
              });
            }
          }
          this.total = res.data.total;
        })
        .catch(error => {
          console.log(error);
        });
    },
    getModelManageToken(val) {
      //获取token值
      window.sessionStorage.removeItem("MacroAuth");
      ModelManageGetApi.getBimApi({
        data: {}
      })
        .then(res => {
          window.sessionStorage.setItem("MacroAuth", res.data);
          if (val == "watch") {
            this.handleCurrentChange(1);
          } else if ((val = "created")) {
            this.handleSizeChange(10);
          }
        })
        .catch(error => {
          console.log(error);
        });
    }
  },
  async created() {
    // await this.getProjectList();//获取
    await this.getMajorTypeCode(); //专业类型
    let store = this.$store.state.choosedProjectList.list;
    let storage = window.localStorage.getItem("choosedProjectList") || "[]";
    let projectList = [];
    projectList = store.length > 0 ? store : JSON.parse(storage);
    this.proArr = projectList;
    this.form.pro_id = projectList[0].project_id || ""; //获取项目主键值
    if (projectList) {
      Promise.all([
        this.getModelManageToken("created") //获取token值
      ]).then(res => {
        // console.log('失败res=', res)
      });
    }
  }
};
</script>
<style   lang="scss" scoped>
.copy-style {
  cursor: pointer;
}
.share-bottom-box {
  text-align: center;
}
.ver-style {
  margin-left: 20px;
}
.opr-button {
  text-align: left;
  margin-bottom: 20px;
}
.sel-style {
  width: 100%;
}
.model-manage {
  padding: 20px;
}
.search-style {
  text-align: right;
}
.bottom-style {
  margin-top: 20px;
  text-align: center;
}
</style>